<?php
declare(strict_types=1);

namespace App\Services\Tools;


use App\Exceptions\BasicException;
use Symfony\Component\HttpClient\HttpClient;

class WechatAppletService
{
    protected $appId;
    protected $secret;

    public function __construct($appId, $secret)
    {
        $this->appId = $appId;
        $this->secret = $secret;
    }

    protected function generateAccessToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?";
        $params = [
            "grant_type" => "client_credential",
            "appid" => $this->appId,
            "secret" => $this->secret,
        ];
        $url .= urldecode(http_build_query($params));

        $client = HttpClient::create();
        $response = $client->request('GET', $url);
        $content = $response->getContent();
        $content = json_decode($content,true);
        if($content["errcode"] != 0){
            throw new BasicException(-1, "wechat applet:" . $content["errmsg"]);
        }
        $token = $content["access_token"];
        $second = $content["expires_in"] - 60;
        RedisService::setWechatAccessToken($this->appId, $token, $second);
        return $token;
    }

    public function getAccessToken()
    {
        $token = RedisService::getWechatAccessToken($this->appId);
        if(empty($token)){
            return $this->generateAccessToken();
        }

        return $token;
    }

    public function generateUrlScheme(string $query, int $expireSecond = 100 * 60, string $path = "")
    {
        $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $this->getAccessToken();
        $param = [
            "expire_type" => 0,
            "expire_time" => time() + $expireSecond,
            "jump_wxa" => [
                "path" => $path,
                "query" => $query,
                // "env_version" => "trial"
            ],
        ];
        $curlService = new \Ixudra\Curl\CurlService();
        $response = $curlService->to($url)
            ->withData($param)
            ->asJson()
            ->post();

        if ($response->errcode != 0){
            $message = $response->errmsg ?: "error";
            throw new BasicException(-1, "wechat applet scheme url:" . $message);
        }
        return $response->openlink;


        // 包底层会转译j.q参数...
        // $url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" . $this->getAccessToken();
        // $params = [
        //     // "access_token" => $this->getAccessToken(),
        //     "expire_type" => 0,
        //     "expire_time" => time() + $expireSecond,
        //     "jump_wxa" => [
        //         "path" => $path,
        //         "query" => $query,
        //         "env_version" => "trial"
        //     ],
        // ];
        // $client = HttpClient::create();
        // $response = $client->request('POST', $url, [
        //     'json' => $params,
        // ]);
        //
        // $content = $response->getContent();
        // $result = json_decode($content,true);
        // if ($result["errcode"] != 0){
        //     throw new BasicException(-1, "wechat applet scheme url:" . $result["errmsg"]);
        // }
        //
        // return $result["openlink"];
    }
}